package com.stx.jeepay.payment.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stx.jeepay.core.entity.PayOrderEntity;
import com.stx.jeepay.core.service.PayOrderService;
import com.stx.jeepay.payment.service.ChannelOrderReissueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 补单定时任务
 */
@Slf4j
@Component
public class PayOrderReissueTask {

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private ChannelOrderReissueService channelOrderReissueService;

    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void start() {
        // 当前时间延后10分钟
        Date offsetDate = DateUtil.offsetMinute(new Date(), -10);

        //查询条件： 支付中的订单 & （ 订单创建时间 + 10分钟 >= 当前时间 ）
        LambdaQueryWrapper<PayOrderEntity> queryWrapper = new LambdaQueryWrapper<PayOrderEntity>();
        queryWrapper.eq(PayOrderEntity::getState, PayOrderEntity.STATE_ING);
        queryWrapper.le(PayOrderEntity::getCreatedAt, offsetDate);

        int currentPageIndex = 1; //当前页码
        while (true) {
            try {
                IPage<PayOrderEntity> page =
                        payOrderService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), queryWrapper);

                if (page == null || page.getRecords() == null || page.getRecords().isEmpty()) {
                    break; // 没查到东西直接退出
                }

                for (PayOrderEntity record : page.getRecords()) {
                    channelOrderReissueService.processPayOrder(record);
                }

                //已经到达页码最大量，无需再次查询
                if (page.getPages() <= currentPageIndex) {
                    break;
                }
                currentPageIndex++;
            } catch (Exception e) {
                // 异常 退出while
                log.error("error", e);
                break;
            }
        }
    }
}
